//
//  AppDelegate.swift
//  Billing
//
//  Created by Dale on 17/4/19.
//  Copyright © 2017年 Nari. All rights reserved.
//

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        self.window = UIWindow(frame: UIScreen.main.bounds)
        // Override point for customization after application launch.
        self.window!.backgroundColor = UIColor.white
                
        globalInit()
        let rootVC = BCLoginViewController();
        window?.rootViewController = rootVC;
        
        
        self.window!.makeKeyAndVisible()
        
        return true
    }
    
    //MARK: -custom func
    func globalInit() {
        Bmob.register(withAppKey: "fda3427c896b8c18dbf6ddab0e515a8f")
        BmobManager.checkAppVersion { (res, status) -> (Void) in
            if status == .NRSSuccess {
                serverVersion = res as! String
                self.checkApp(serVersion: res as! String)
            }
        }
        
        //个推
        let messageManager = MessageManager.defaultMessageManager
        messageManager.startGeTui()
        messageManager.registerRemoteNotification()
        
    }
    
    func checkApp(serVersion: String) -> Void {
        let alert = AlertView.main()
        let serArr:[String] = serVersion.components(separatedBy: ".")
        let appArr:[String] = appVersion.components(separatedBy: ".")
        if serArr.count == 3 && appArr.count == 3 {
            if serArr[0] != appArr[0] {
                isHasNewVersion = true
                isHasBigVersion = true
                alert?.updateVewsin(true, updateInfo: serVersion)
                return
            }
            if serArr[1] != appArr[1] {
                isHasNewVersion = true
                isHasBigVersion = false
                alert?.updateVewsin(false, updateInfo: serVersion)
                return
            }
            if serArr[2] != appArr[2] {
                isHasNewVersion = true
                isHasBigVersion = false
                alert?.updateVewsin(false, updateInfo: serVersion)
                return
            }
            isHasNewVersion = false
            isHasBigVersion = false
        }
    }
    
    
    // MARK: - 远程通知(推送)回调
    
    /** 远程通知注册成功委托 */
    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        let deviceToken_ns = NSData.init(data: deviceToken);    // 转换成NSData类型
        var token = deviceToken_ns.description.trimmingCharacters(in: CharacterSet(charactersIn: "<>"));
        token = token.replacingOccurrences(of: " ", with: "")
        
        // [ GTSdk ]：向个推服务器注册deviceToken
        GeTuiSdk.registerDeviceToken(token);
        
        print("\n>>>[DeviceToken Success]:\(token)");
    }
    
    /** 远程通知注册失败委托 */
    func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
        print("\n>>>[DeviceToken Error]:\(error.localizedDescription)");
    }
    
    // MARK: - APP运行中接收到通知(推送)处理 - iOS 10 以下
    /** APP已经接收到“远程”通知(推送) - (App运行在后台) */
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any]) {
        application.applicationIconBadgeNumber = 0;        // 标签
        
        print("\n>>>[Receive RemoteNotification]:\(userInfo)");
    }
    
    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable: Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        
        // [ GTSdk ]：将收到的APNs信息传给个推统计
        GeTuiSdk.handleRemoteNotification(userInfo);
        
        print("\n>>>[Receive RemoteNotification]:\(userInfo)");
        completionHandler(UIBackgroundFetchResult.newData);
    }

    func application(_ application: UIApplication, didRegister notificationSettings: UIUserNotificationSettings) {
        application.registerForRemoteNotifications()
    }
    
    func applicationWillResignActive(_ application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(_ application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(_ application: UIApplication) {
        // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(_ application: UIApplication) {
        application.applicationIconBadgeNumber = 0
        let messageManager = MessageManager.defaultMessageManager
        messageManager.startGeTui()
    }

    func applicationWillTerminate(_ application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }
}

